#include "ebook.h"
#include <stdio.h>
#include <string>
#include <fstream>
#include <sstream>
#include "../utils/fileutils.h"
#include "dictionary.h"
#include "../exceptions/filenotfoundexception.h"
#include "../exceptions/openfileexception.h"
#include "exceptions/nullpathexception.h"

using namespace std;

EBook::EBook(const char* eBookPath, const char* dictionaryPath)
{
    dictionary_ = new Dictionary(dictionaryPath);
    readEBook(eBookPath);
}

bool EBook::addPage(const EBookPage& page)
{
    pages_.push_back(page);
    return true;
}

void trimLine(std::string& line)
{
    line.erase(line.find_last_not_of(" \n\r\t")+1);
    line.erase(0, line.find_first_not_of(" \n\r\t"));
}

void EBook::findWordsToIndex(EBookPage& page)
{
    for (list<string>::iterator it = dictionary_->words.begin(); it != dictionary_->words.end(); it++)
    {
        if (page.containsWord(*it))
        {
            Word w(*it);
            index_.addWord(w, page.number);
        }
    }
}

void EBook::readEBook(const char* eBookPath) throw (FileException)
{
    if(!eBookPath)
        throw NullPathException();
    if(!exist(eBookPath))
        throw FileNotFoundExpcetion(eBookPath);
    
    ifstream file(eBookPath);
    if(!file.is_open())
        throw OpenFileException(eBookPath);
    
    int pageNumber = 0;
    string buffer;
    EBookPage page;
    while(getline(file, buffer))
    {
        trimLine(buffer);
        if(buffer == PAGE_BREAK)
        {
            pageNumber++;
            page.number = pageNumber;
            addPage(page);
            findWordsToIndex(page);
            page.data.clear();
        }
        else
        {
            page.addLine(buffer);
        }
    }
    pages_.push_back(page);
    file.close();
}
